<template>
  <div class="app-container full-width">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车次编号" prop="trainCode">
        <el-select
          v-model="queryParams.trainCode"
          filterable
          remote
          clearable
          placeholder="请输入车次编号"
          :remote-method="remoteMethodTrain"
          :loading="loading"
          size="small"
          style="width: 200px"
          allow-create
        >
          <el-option
            v-for="item in trainOptions"
            :key="item.code"
            :label="item.code"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查找</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['base:train-station:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:train-station:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:train-station:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['base:train-station:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['base:train-station:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClear"
          v-hasPermi="['base:train-station:remove']"
        >清空数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-show="showImportError"
          type="danger"
          plain
          icon="el-icon-document"
          size="mini"
          @click="handleExportErrorData"
        >导出错误数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-show="showImportError"
          type="warning"
          plain
          icon="el-icon-document-copy"
          size="mini"
          @click="handleCopyErrorData"
        >复制到剪贴板</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 折叠面板列表 -->
    <el-collapse v-model="activeNames">
      <el-collapse-item v-for="group in trainStationList" :key="group.trainCode" :name="group.trainCode">
        <template slot="title">
          <div class="train-collapse-title">
            <span class="train-code">{{ group.trainCode }}</span>
            <span class="route-info">
              <span class="start-station">{{ group.firstStation }}</span>
              <i class="el-icon-arrow-right route-arrow"></i>
              <span class="end-station">{{ group.lastStation }}</span>
            </span>
            <span class="route-stats">
              <span class="total-km" v-if="group.totalKm">总里程: {{ group.totalKm }}公里</span>
              <span class="total-time" v-if="group.totalTime">行程时间: {{ group.totalTime }}</span>
            </span>
          </div>
        </template>

        <!-- 站点列表 -->
        <el-table :data="group.stations" style="width: 100%; min-width: 800px;" border size="small" @selection-change="handleSelectionChange" >
          <el-table-column show-overflow-tooltip type="selection" width="55" align="center" />
<!--          <el-table-column show-overflow-tooltip label="id"  align="center" prop="id" />-->
          <el-table-column label="站序" align="center" prop="index" min-width="60">
            <template slot-scope="scope">
              <span>{{ scope.row.index === 0 ? '0' : (scope.row.index || '--') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="站名" align="center" prop="name" min-width="120"/>
          <el-table-column label="进站时间" align="center" min-width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.index === 0">— —</span>
              <span v-else>{{ formatTimeDisplay(scope.row.inTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="出站时间" align="center" min-width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.outTime && scope.row.outTime.toString() === '00:00:00'">— —</span>
              <span v-else>{{ formatTimeDisplay(scope.row.outTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="停站时长" align="center" min-width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.index === 0 || (scope.row.outTime && scope.row.outTime.toString() === '00:00:00')">— —</span>
              <span v-else>{{ formatTimeDisplay(scope.row.stopTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="里程(公里)" align="center" prop="km" min-width="100"/>
          <el-table-column label="操作" align="center" min-width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['base:train-station:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['base:train-station:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <pagination
      v-show="trainTotal>0"
      :total="trainTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改途径车站对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车次编号" prop="trainCode">
          <el-select
            v-model="form.trainCode"
            filterable
            placeholder="请选择车次"
            style="width: 100%"
            @change="handleTrainCodeChange"
            :disabled="form.id != null"
          >
            <el-option
              v-for="item in trainOptions"
              :key="item.code"
              :label="item.code"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="站序" prop="index">
          <el-input
            v-model="form.index"
            placeholder="站序"
            :disabled="true">
            <template slot="suffix">
              <i class="el-icon-lock" style="color: #F56C6C;"></i>
            </template>
          </el-input>
          <div v-if="form.index === '0' || form.index === 0" class="form-tip" style="color: #E6A23C;">
            <i class="el-icon-warning"></i>这是起始站，站序不可修改
          </div>
        </el-form-item>
        <el-form-item label="站名" prop="name">
          <el-select
            v-model="form.name"
            filterable
            placeholder="请选择站名"
            @change="handleStationSelect"
            style="width: 100%"
            :disabled="isFieldDisabled || form.index === 0"
          >
            <el-option
              v-for="(item, index) in stationOptions.filter(station => !selectedStations.includes(station.value) || station.value === form.name)"
              :key="index + '_' + item.value"
              :label="item.label"
              :value="item.value"
              style="width: 300px"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="站名拼音" prop="namePinyin">
          <el-input v-model="form.namePinyin" :disabled="true"/>
        </el-form-item>
        <el-form-item label="进站时间" prop="inTime">
          <el-time-picker
            v-model="form.inTime"
            placeholder="请选择时间"
            :disabled="isFieldDisabled || form.index === 0 || (form.name === currentTrainEndStation)"
            value-format="HH:mm:ss"
            format="HH:mm:ss"
            @change="handleInTimeChange"
          />
          <div v-if="lastStationOutTime && form.index !== '0' && form.index !== 0" class="form-tip" style="color: #909399;">
            <i class="el-icon-info-circle"></i>上一站出站时间: {{lastStationOutTime}}
          </div>
        </el-form-item>
        <el-form-item label="出站时间" prop="outTime">
          <el-time-picker
            v-model="form.outTime"
            placeholder="请选择时间"
            :disabled="isFieldDisabled || form.index === 0 || !form.inTime || (form.name === currentTrainEndStation)"
            value-format="HH:mm:ss"
            format="HH:mm:ss"
            @change="handleOutTimeChange"
          />
        </el-form-item>
        <el-form-item label="停站时长" prop="stopTime">
          <el-time-picker
            clearable
            v-model="form.stopTime"
            value-format="HH:mm:ss"
            :disabled="true">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="里程" prop="km">
          <el-input
            v-model="form.km"
            placeholder="系统自动计算"
            :disabled="true"
          />
          <span v-if="form.index > 0" style="color:#409EFF;font-size:12px;">系统会自动计算与上一站的距离</span>
          <span v-else style="color:#F56C6C;font-size:12px;">起始站里程数固定为0</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="!form.trainCode">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="title" :visible.sync="importOpen" width="500px" append-to-body>
      <div class="import-tip" style="margin-bottom: 15px;">
        <p style="margin: 0 0 10px 0; font-weight: bold;">请按以下格式准备Excel文件：</p>
        <el-card class="box-card" shadow="never">
          <div class="text item">
            <p style="margin: 5px 0;">1. ID（可选，新增时自动生成）</p>
            <p style="margin: 5px 0;">2. 车次编号（必填）：如 G1234</p>
            <p style="margin: 5px 0;">3. 站序（必填）：如 0、1、2</p>
            <p style="margin: 5px 0;">4. 站名（必填）：如 北京西站</p>
            <p style="margin: 5px 0;">5. 站名拼音（选填）：如 beijingxizhan</p>
            <p style="margin: 5px 0;">6. 进站时间（必填）：如 08:30:00</p>
            <p style="margin: 5px 0;">7. 出站时间（必填）：如 08:35:00</p>
            <p style="margin: 5px 0;">8. 停站时长（系统自动计算）：如 00:05:00</p>
            <p style="margin: 5px 0;">9. 里程（必填，起始站为0）：如 0、50、150（单位：公里）</p>
          </div>
        </el-card>
        <div style="margin-top: 15px; color: #E6A23C; font-size: 13px;">
          <i class="el-icon-warning"></i> 注意：
          <ul style="margin: 5px 0 0 0; padding-left: 20px;">
            <li>车次编号必须已存在于列车管理中</li>
            <li>同一车次内，站序和站名不能重复</li>
            <li>第一站（站序为0）的里程必须为0</li>
          </ul>
        </div>
        <div style="margin-top: 15px; display: flex; gap: 10px;">
          <el-link
            type="primary"
            @click="showExampleImage">
            <i class="el-icon-view"></i> 查看Excel模板示例
          </el-link>
          <el-link
            type="primary"
            @click="handleDownloadTemplate">
            <i class="el-icon-download"></i> 下载Excel模板
          </el-link>
        </div>
      </div>
      <el-upload
        ref="upload"
        class="upload-demo"
        :action="uploadExcelUrl"
        :headers="headers"
        :on-success="handleExcelSuccess"
        :on-error="handleExcelError"
        :auto-upload="false"
        :before-upload="beforeUpload"
        :limit="1"
        :on-exceed="handleExceed"
        :on-change="handleFileChange"
        accept=".xlsx, .xls"
      >
        <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload" :disabled="!fileSelected">上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且不超过5MB</div>
      </el-upload>
    </el-dialog>

    <!-- 添加示例图片对话框 -->
    <el-dialog
      title="Excel模板示例"
      :visible.sync="exampleImageVisible"
      width="830px"
      custom-class="zero-padding-dialog"
      :append-to-body="true"
    >
      <div style="padding: 0; overflow-x: auto; width: 100%;">
        <table class="compact-table" style="min-width: 930px;">
          <thead>
            <tr>
              <th width="200">ID</th>
              <th width="80">车次编号</th>
              <th width="60">站序</th>
              <th width="100">站名</th>
              <th width="120">站名拼音</th>
              <th width="100">进站时间</th>
              <th width="100">出站时间</th>
              <th width="100">停站时长</th>
              <th width="70">里程</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>1577098763758821376</td>
              <td>G1234</td>
              <td>0</td>
              <td>北京西站</td>
              <td>beijingxizhan</td>
              <td>08:00:00</td>
              <td>08:05:00</td>
              <td>00:05:00</td>
              <td>0</td>
            </tr>
            <tr>
              <td>1577098763758821377</td>
              <td>G1234</td>
              <td>1</td>
              <td>天津南站</td>
              <td>tianjinnanzhan</td>
              <td>08:45:00</td>
              <td>08:48:00</td>
              <td>00:03:00</td>
              <td>150</td>
            </tr>
          </tbody>
        </table>
      </div>

      <div style="margin-top: 15px; padding: 10px; background-color: #f8f8f8; border-radius: 4px; font-size: 13px;">
        <p style="font-weight: bold; margin-bottom: 8px;">数据验证规则：</p>
        <ul style="padding-left: 20px; margin: 0;">
          <li>车次编号必须已存在于列车管理中</li>
          <li>同一车次内，站序不能重复</li>
          <li>同一车次内，站名不能重复</li>
          <li>站点时间不能冲突，出站时间必须大于进站时间</li>
          <li>第一站（站序为0）的里程必须为0</li>
        </ul>
        </div>
      <div style="margin-top: 10px; padding: 5px; color: #666; text-align: center; font-size: 12px;">
        <i class="el-icon-info-circle"></i> 提示：如果表格内容显示不全，可左右滑动查看
        </div>
    </el-dialog>

    <!-- 导入错误数据对话框 -->
    <el-dialog
      :title="'导入结果: ' + importSuccessCount + ' 条成功，' + importErrorData.length + ' 条错误'"
      :visible.sync="importErrorVisible"
      width="1000px"
      append-to-body
    >
      <el-alert
        v-if="importSuccessCount > 0"
        type="warning"
        :title="'部分数据导入成功: ' + importSuccessCount + ' 条有效记录已保存到数据库，下表显示 ' + importErrorData.length + ' 条有错误的记录'"
        :closable="false"
        show-icon
        style="margin-bottom: 10px"
      >
      </el-alert>
      <el-alert
        v-else
        type="error"
        :title="'导入失败: 所有 ' + importErrorData.length + ' 条记录都有错误，未能导入任何数据'"
        :closable="false"
        show-icon
        style="margin-bottom: 10px"
      >
      </el-alert>

      <p>错误分析：
        <span v-if="getErrorCount('train code').count > 0">
          车次编号错误 {{getErrorCount('train code').count}} 条;
        </span>
        <span v-if="getErrorCount('duplicated').count > 0">
          重复数据 {{getErrorCount('duplicated').count}} 条;
        </span>
        <span v-if="getErrorCount('index').count > 0">
          站序错误 {{getErrorCount('index').count}} 条;
        </span>
        <span v-if="getErrorCount('name').count > 0">
          站名错误 {{getErrorCount('name').count}} 条;
        </span>
        <span v-if="getErrorCount('time').count > 0">
          时间错误 {{getErrorCount('time').count}} 条;
        </span>
        <span v-if="getErrorCount('format').count > 0">
          格式错误 {{getErrorCount('format').count}} 条;
        </span>
      </p>

      <div class="error-operation">
        <el-button
          type="warning"
          @click="handleExportErrorData"
          icon="el-icon-download"
          >导出错误数据</el-button
        >
        <el-button type="primary" @click="handleCopyErrorData" icon="el-icon-copy-document"
          >复制错误消息</el-button
        >
        <el-button
          type="success"
          @click="handleDownloadTemplate"
          icon="el-icon-download"
          >下载正确模板</el-button
        >
      </div>

        <el-table
          :data="importErrorData"
          border
        style="width: 100%; margin-top: 15px;"
        :height="importErrorData.length > 10 ? '400' : 'auto'"
        :default-sort="{prop: 'rowNum', order: 'ascending'}"
        >
        <el-table-column
          prop="rowNum"
          label="行号"
          width="70"
          sortable>
          </el-table-column>
        <el-table-column
          prop="trainCode"
          label="车次编号"
          width="100"
          sortable
          column-key="trainCode"
          :filters="getTrainCodeFilters()"
          :filter-method="filterTrainCode">
          </el-table-column>
        <el-table-column
          label="站序"
          width="70"
          sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.index === 0">0</span>
            <span v-else-if="scope.row.index">{{ scope.row.index }}</span>
            <span v-else>--</span>
          </template>
          </el-table-column>
        <el-table-column
          prop="name"
          label="站名"
          width="120"
          sortable
          show-overflow-tooltip>
          </el-table-column>
        <el-table-column
          prop="namePinyin"
          label="站名拼音"
          width="120"
          :show-overflow-tooltip="true">
          </el-table-column>
        <el-table-column
          prop="inTime"
          label="进站时间"
          width="100">
          </el-table-column>
        <el-table-column
          prop="outTime"
          label="出站时间"
          width="100">
          </el-table-column>
        <el-table-column
          prop="stopTime"
          label="停站时长"
          width="100">
          </el-table-column>
        <el-table-column
          prop="km"
          label="里程（公里）"
          width="120"
          sortable>
          </el-table-column>
        <el-table-column
          prop="errorMsg"
          label="错误原因"
          :show-overflow-tooltip="true"
          :filters="getErrorTypeFilters()"
          :filter-method="filterErrorType">
            <template slot-scope="scope">
            <el-tooltip placement="top" :content="scope.row.errorMsg">
              <div>
                <span style="color: #F56C6C;">
                  <i class="el-icon-warning"></i>
                  {{scope.row.errorMsg}}
                </span>
              </div>
            </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="importErrorVisible = false">关 闭</el-button>
        <el-button type="primary" @click="handleRetryImport">重新导入</el-button>
      </div>
    </el-dialog>

    <!-- 清空对话框 -->
    <el-dialog :title="title" :visible.sync="clearOpen" width="500px" append-to-body>
      <el-form ref="clearForm" :model="clearForm" :rules="clearRules" label-width="80px">
        <el-form-item label="密码" prop="password">
          <el-input v-model="clearForm.password" type="password" placeholder="请输入登录密码" show-password/>
          <div style="color: #F56C6C; font-size: 12px; margin-top: 8px;">提示：清空操作将删除所有列车站点数据且不可恢复，请谨慎操作！</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitClearForm">确 定</el-button>
        <el-button @click="cancelClear">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPlatformList } from "@/api/base/platform";
import {
  listTrainStation,
  getTrainStation,
  delTrainStation,
  addTrainStation,
  updateTrainStation,
  listAllStationsByTrainCode,
  clearTrainStation
} from "@/api/base/train-station";
import { listTrain } from "@/api/base/train";

export default {
  name: "Train-station",
  data() {
    return {
      // 车次部分
      trainOptions: [],
      // 站点选项
      stationOptions: [],
      // 高德地图API
      AMap: null,
      // 高德地图地理编码服务
      geocoder: null,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 选中数组
      names:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车次总数（用于分页）
      trainTotal: 0,
      // 途径车站表格数据
      trainStationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入对话框显示状态
      importOpen: false,
      // 示例图片对话框
      exampleImageVisible: false,
      // 已折叠的车次编号集合
      activeNames: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        trainCode: null,
      },
      // 表单参数
      form: {
        id: null,
        trainCode: null,
        index: null,
        name: null,
        namePinyin: null,
        inTime: null,
        outTime: null,
        stopTime: null,
        km: null,
        indexLocked: false
      },
      // 表单校验
      rules: {
        trainCode: [
          { required: true, message: "车次编号不能为空", trigger: "blur" }
        ],
        index: [
          { required: true, message: "站序不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "站名不能为空", trigger: "blur" }
        ],
        inTime: [
          { required: true, message: "进站时间不能为空", trigger: "blur" }
        ],
        outTime: [
          { required: true, message: "出站时间不能为空", trigger: "blur" }
        ],
        km: [
          { required: true, message: "里程不能为空", trigger: "blur" }
        ]
      },
      // 导入相关
      importErrorData: [],
      importErrorVisible: false,
      showImportError: false,
      fileSelected: false,
      distanceLoading: false,
      // 上传相关
      uploadExcelUrl: process.env.VUE_APP_BASE_API + "/base/train-station/importExcel",
      headers: {'Authorization': 'Bearer ' + this.$store.getters.token},
      // 成功导入的数据条数
      importSuccessCount: 0,
      // 清空对话框相关
      clearOpen: false,
      clearForm: {
        password: ''
      },
      clearRules: {
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      },
      selectedStations: [], // 当前车次已选择的站点
      lastStationOutTime: null, // 上一站的出站时间
      disableAllFieldsExceptTrain: false,
      isEndStationExists: false, // 新增：标记是否已存在终点站
      currentTrainEndStation: null, // 当前选择的列车终点站
      currentTrainArrivalTime: null, // 当前选择的列车到站时间
      currentTrainInfo: null, // 存储完整的列车信息
    };
  },
  computed: {
    // 新增计算属性：控制表单字段的禁用状态
    isFieldDisabled() {
      return this.disableAllFieldsExceptTrain || this.isEndStationExists;
    }
  },
  watch: {
    // 监听表单数据变化，确保起始站里程为0
    'form.index': function(newVal) {
      if (newVal === '0' && this.form.km !== '0') {
        this.form.km = '0';
      }
    },
    'form.km': function(newVal) {
      if (this.form.index === '0' && newVal !== '0') {
        this.form.km = '0';
        this.$message.warning('起始站里程必须为0，已自动修正');
      }
    }
  },
  created() {
    // 获取车次列表
    this.getTrainList();
    // 获取站点列表
    this.getStationList();
    // 初始化高德地图API
    this.initAMap();
    // 获取列表数据
    this.getList();

    // 初始化错误状态
    const errorData = sessionStorage.getItem('trainStationImportError');
    if (errorData) {
      try {
        this.importErrorData = JSON.parse(errorData);
        this.showImportError = this.importErrorData && this.importErrorData.length > 0;
        console.log("初始化错误状态:", {
          hasErrorData: !!this.importErrorData,
          errorCount: this.importErrorData ? this.importErrorData.length : 0,
          showImportError: this.showImportError
        });
      } catch (e) {
        console.error("解析错误数据失败:", e);
        this.importErrorData = [];
        this.showImportError = false;
      }
    }
  },
  methods: {
    // 获取车次列表
    getTrainList() {
      listTrain().then(response => {
        this.trainOptions = response.rows;
      });
    },
    // 获取站点列表
    getStationList() {
      getPlatformList().then(response => {
        this.stationOptions = response.map((item, index) => ({
          value: item.stationName,
          label: `${item.stationName} ${item.stationPinyin}~${item.stationInitials.toLowerCase()}`,
          pinyin: item.stationPinyin,
          stationName: item.stationName,
          uniqueId: `${item.stationName}-${index}`
        }));
      });
    },
    // 初始化高德地图API
    initAMap() {
      return new Promise((resolve, reject) => {
        // 首先设置安全配置
        window._AMapSecurityConfig = {
          securityJsCode: 'efe5df61770675b2985df3e32565fb80'  // 安全密钥
        };

        // 检查是否已加载
        if (window.AMap) {
          this.AMap = window.AMap;
          // 确保插件加载完成后再初始化
          this.AMap.plugin(['AMap.Geocoder', 'AMap.GeometryUtil'], () => {
            this.geocoder = new this.AMap.Geocoder({
              city: "全国" // 指定查询范围为全国
            });
            console.log("高德地图API初始化成功");
            resolve();
          });
          return;
        }

        // 动态加载高德地图JS
        const script = document.createElement('script');
        script.src = `https://webapi.amap.com/maps?v=1.4.15&key=05d4c031a356cdffb8055c0d1532ced8`;  // API key

        script.onload = () => {
          if (window.AMap) {
            this.AMap = window.AMap;
            // 加载完成后加载插件
            this.AMap.plugin(['AMap.Geocoder', 'AMap.GeometryUtil'], () => {
              try {
                this.geocoder = new this.AMap.Geocoder({
                  city: "全国" // 指定查询范围为全国
                });
                console.log("高德地图API初始化成功");
                resolve();
              } catch (err) {
                console.error('Geocoder 插件初始化失败', err);
                reject(new Error('Geocoder 插件初始化失败'));
              }
          });
        } else {
            console.error('AMap 加载失败');
            reject(new Error('AMap 加载失败'));
          }
        };

        script.onerror = () => {
          console.error('高德地图脚本加载失败');
          reject(new Error('高德地图脚本加载失败'));
        };

        document.head.appendChild(script);
      });
    },
    // 远程搜索车次
    remoteMethodTrain(query) {
      if (query !== '') {
        this.loading = true;
      setTimeout(() => {
          this.loading = false;
          this.trainOptions = this.trainOptions.filter(item => {
            return item.code.toLowerCase().includes(query.toLowerCase());
          });
        }, 200);
      } else {
        this.getTrainList();
      }
    },
    // 获取列表数据
    getList() {
      this.loading = true;
      listTrainStation(this.queryParams).then(response => {
        this.trainStationList = response.rows;
        console.log(this.trainStationList,"!@#!@#!@!#@#!@@!#!#@!@#!#@")
        this.trainTotal = response.total;
        this.loading = false;
      });
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 新增按钮操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加途径车站";

      // 禁用除车次编号外的所有字段，直到选择车次
      this.disableAllFieldsExceptTrain = true;

      // 如果查询参数中已经有车次编号，则自动选择并触发查询
      if (this.queryParams.trainCode) {
        this.form.trainCode = this.queryParams.trainCode;
        this.$nextTick(() => {
          this.handleTrainCodeChange(this.queryParams.trainCode);
        });
      }
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getTrainStation(id).then(response => {
        this.form = response.data;
        // 修改时不锁定站序
        this.form.indexLocked = false;
        this.open = true;
        this.title = "修改途径车站";

        // 获取当前列车的终点站信息
        listTrain().then(trainResponse => {
          if (trainResponse.rows && trainResponse.rows.length > 0) {
            const currentTrain = trainResponse.rows.find(train => train.code === this.form.trainCode);
            if (currentTrain) {
              this.currentTrainEndStation = currentTrain.end;
              this.currentTrainArrivalTime = currentTrain.endTime;

              // 如果是终点站，锁定时间
              if (this.form.name === this.currentTrainEndStation) {
                this.form.inTime = this.currentTrainArrivalTime;
                this.form.outTime = "00:00:00";
                this.form.stopTime = "00:00:00";
              }
            }
          }
        });

        // 设置字段禁用状态
        this.disableAllFieldsExceptTrain = false;
      });
    },
    // 删除按钮操作
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names= row.name || this.names;
      this.$modal.confirm('是否确认删除列车途径车站站点为"' + names + '"的数据项？').then(function() {
        return delTrainStation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        trainCode: null,
        index: null,
        name: null,
        namePinyin: null,
        inTime: null,
        outTime: null,
        stopTime: null,
        km: null,
        indexLocked: false
      };
      this.resetForm("form");
      this.selectedStations = [];
      this.lastStationOutTime = null;
      this.disableAllFieldsExceptTrain = true;
      this.currentTrainEndStation = null;
      this.currentTrainArrivalTime = null;
    },
    // 表单提交
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTrainStation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTrainStation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    this.names = selection.map(item => item.name);
    this.single = selection.length !== 1;
    this.multiple = selection.length === 0;
    console.log('Selection changed:', {
      ids: this.ids,
      names: this.names,
      single: this.single,
      multiple: this.multiple,
      selectionLength: selection.length
    });
    },
    // 车次编号变更
    handleTrainCodeChange(value) {
      console.log("车次编号变更:", value);
      if (!value) {
        this.disableAllFieldsExceptTrain = true;
        this.isEndStationExists = false;
        return;
      }

      // 先获取列车基本信息
      listTrain().then(response => {
        if (response.rows && response.rows.length > 0) {
          const currentTrain = response.rows.find(train => train.code === value);
          console.log("获取到的完整列车信息:", currentTrain);

          if (currentTrain) {
            this.currentTrainInfo = currentTrain;
            this.currentTrainEndStation = currentTrain.end;
            this.currentTrainArrivalTime = currentTrain.endTime;
          }
        }
      }).catch(error => {
        console.error("获取列车信息失败:", error);
      });

      // 查询该车次的所有站点
      listAllStationsByTrainCode(value).then(response => {
        if (response.code === 200 && response.data) {
          const stations = response.data;
          console.log("查询到站点数据:", stations);

          // 检查是否已有终点站
          const hasEndStation = stations.some(station =>
            station.name && this.currentTrainEndStation &&
            station.name.trim() === this.currentTrainEndStation.trim()
          );

          // 更新终点站状态
          this.isEndStationExists = hasEndStation;
          this.disableAllFieldsExceptTrain = hasEndStation;

          if (hasEndStation) {
            // 如果已有终点站，提示用户并清空表单
            this.$message({
              message: `此列车(${value})的途径站点已到终点站，不能继续添加站点`,
              type: 'error',
              duration: 5000
            });
            // 清空表单数据
            this.form.index = null;
            this.form.name = null;
            this.form.namePinyin = null;
            this.form.inTime = null;
            this.form.outTime = null;
            this.form.stopTime = null;
            this.form.km = null;
            return;
          }

          // 更新已选站点列表
          this.selectedStations = stations.map(station => station.name);

          if (stations.length === 0) {
            // 没有站点，设置为第一站（站序为0）
            this.form.index = 0;
            this.form.indexLocked = true;
            this.form.km = "0";

            // 如果有列车信息，自动填充起始站信息
            if (this.currentTrainInfo) {
              console.log("准备填充起始站信息:", this.currentTrainInfo);

              // 自动填充起始站名称（尝试多个可能的字段名）
              const startStationName = this.currentTrainInfo.startStation || this.currentTrainInfo.start || this.currentTrainInfo.startStationName;
              if (startStationName) {
                this.form.name = startStationName;
                console.log("已设置起始站名称:", startStationName);

                // 查找对应的站点信息以获取拼音
                const startStation = this.stationOptions.find(station => station.value === startStationName);
                if (startStation) {
                  this.form.namePinyin = startStation.pinyin;
                  console.log("已设置起始站拼音:", startStation.pinyin);
                } else {
                  // 如果在stationOptions中找不到，尝试使用列车信息中的拼音
                  this.form.namePinyin = this.currentTrainInfo.startStationPinyin || '';
                  console.log("使用列车信息中的拼音:", this.form.namePinyin);
                }
              }

              // 自动填充进站和出站时间
              const startTime = this.currentTrainInfo.startTime || this.currentTrainInfo.departureTime;
              if (startTime) {
                this.form.inTime = startTime;
                this.form.outTime = startTime; // 出站时间与进站时间相同
                console.log("已设置进站和出站时间:", startTime);
              }
            }

            console.log("第一站信息设置完成，表单当前状态:", this.form);
          } else {
            // 找到最大站序
            const maxIndex = Math.max(...stations.map(station => station.index));
            this.form.index = maxIndex + 1;
            this.form.indexLocked = true;

            // 获取上一站的出站时间
            const lastStation = stations.find(station => station.index === maxIndex);
            if (lastStation) {
              this.lastStationOutTime = lastStation.outTime;
              console.log("上一站出站时间:", this.lastStationOutTime);
            }
          }

          // 启用其他字段（只有在没有终点站的情况下）
          this.disableAllFieldsExceptTrain = false;
        }
      }).catch(error => {
        console.error("查询站点异常:", error);
        this.$message.error("获取站点信息失败");
      });
    },
    // 站序变更
    handleIndexChange(value) {
      if (value === "0" || value === 0) {
        this.form.km = "0";
        this.form.indexLocked = true;
      } else {
        this.form.indexLocked = false;
      }
    },
    // 站点选择
    handleStationSelect(value) {
      console.log("站点选择变更:", value);
      const selectedStation = this.stationOptions.find(item => item.value === value);
      if (selectedStation) {
        // 检查站点是否已被选择
        if (this.selectedStations.includes(selectedStation.value)) {
          this.$message.error("该站点已在当前车次中使用");
          this.form.name = "";
          return;
        }

        this.form.namePinyin = selectedStation.pinyin;
        this.form.name = selectedStation.value;
        // 使用预先获取的终点站信息进行比较
        if (this.currentTrainEndStation && this.currentTrainArrivalTime) {
          const currentStationName = String(selectedStation.value).trim();
          const endStationName = String(this.currentTrainEndStation).trim();

          console.log("终点站比较:", {
            当前选择的站名: currentStationName,
            终点站名: endStationName,
            是否匹配: currentStationName === endStationName,
            到站时间: this.currentTrainArrivalTime
          });

          if (currentStationName === endStationName) {
            console.log("匹配到终点站，准备设置时间...");

            // 使用setTimeout确保在下一个事件循环中设置时间
            setTimeout(() => {
              // 设置进站时间为列车到达时间
              this.form.inTime = this.currentTrainArrivalTime;
              // 终点站固定出站时间和停站时间为00:00:00
              this.form.outTime = "00:00:00";
              this.form.stopTime = "00:00:00";

              // 在template中添加:disabled属性
              this.$nextTick(() => {
                const inTimePicker = this.$el.querySelector('.in-time-picker');
                const outTimePicker = this.$el.querySelector('.out-time-picker');
                if (inTimePicker) inTimePicker.setAttribute('disabled', 'disabled');
                if (outTimePicker) outTimePicker.setAttribute('disabled', 'disabled');
              });

              console.log("终点站时间已设置并锁定");
            }, 0);
            this.$message.success(`已自动设置终点站时间并锁定：进站 ${this.currentTrainArrivalTime}，出站和停站时间已固定为00:00:00`);
          } else {
            console.log("不是终点站，需要手动设置时间");
          }
        } else {
          console.warn("终点站信息不完整:", {
            终点站名: this.currentTrainEndStation,
            到站时间: this.currentTrainArrivalTime
          });
        }

        if (this.form.index !== 0 && this.form.index !== '0') {
          this.calculateDistanceWithGaode();
        }
      }
    },
    // 进站时间变更
    handleInTimeChange(time) {
      if (!time) return;

      // 检查是否小于上一站出站时间
      if (this.lastStationOutTime && this.form.index !== 0) {
        const inTime = new Date(`2000/01/01 ${time}`);
        const lastOutTime = new Date(`2000/01/01 ${this.lastStationOutTime}`);

        if (inTime < lastOutTime) {
          this.$message.error(`进站时间不能早于上一站出站时间 ${this.lastStationOutTime}`);
          this.form.inTime = null;
          return;
        }
      }

      // 如果已设置出站时间，重新计算停站时长
      if (this.form.outTime) {
        this.calculateStopTime();
      }
    },
    // 使用高德地图API计算距离
    calculateDistanceWithGaode() {
      if (!this.form.name || !this.form.trainCode) {
        this.$message.warning("请先选择车次和站点");
        return;
      }

      if (this.form.index === 0 || this.form.index === '0') {
        this.form.km = "0";
        this.$message.info("起始站里程固定为0");
        return;
      }

      this.distanceLoading = true;

      // 获取上一站信息
      const prevIndex = parseInt(this.form.index) - 1;
      const queryParams = {
        trainCode: this.form.trainCode,
        index: prevIndex
      };

      console.log("查询上一站参数:", JSON.stringify(queryParams));

      // 尝试使用不同的方法获取上一站数据
      listAllStationsByTrainCode(this.form.trainCode).then(response => {
        console.log("获取所有站点:", response);

        if (response.code === 200 && response.data) {
          // 查找上一站
          const prevStation = response.data.find(station => station.index === prevIndex);

          if (prevStation) {
            console.log("找到上一站:", prevStation);

            // 确保高德地图API已初始化
            if (!this.geocoder || !this.AMap) {
              this.initAMap().then(() => {
                this.calculateGaodeDistance(prevStation.name, this.form.name, prevStation.km);
              }).catch(err => {
                this.$message.error("初始化高德地图API失败: " + err.message);
                this.distanceLoading = false;

                // 降级处理：使用简单的预估距离
                const kmValue = (parseFloat(prevStation.km || 0) + 50).toFixed(1);
                this.form.km = kmValue;
                this.$message.warning(`API调用失败，使用预估里程：${kmValue}公里`);
              });
            } else {
              this.calculateGaodeDistance(prevStation.name, this.form.name, prevStation.km);
            }
          } else {
            console.error("在所有站点中未找到上一站:", prevIndex);
            // 作为备选方案，使用原来的查询方法
            this.fallbackQueryPrevStation(queryParams);
          }
        } else {
          console.error("获取所有站点失败:", response);
          // 作为备选方案，使用原来的查询方法
          this.fallbackQueryPrevStation(queryParams);
        }
      }).catch(err => {
        console.error("获取所有站点错误:", err);
        // 作为备选方案，使用原来的查询方法
        this.fallbackQueryPrevStation(queryParams);
      });
    },

    // 备选方案：使用原来的方法查询上一站
    fallbackQueryPrevStation(queryParams) {
      console.log("使用备选方案查询上一站:", queryParams);

      listTrainStation(queryParams).then(response => {
        console.log("备选方案查询结果:", response);

        if (response.rows && response.rows.length > 0) {
          const prevStation = response.rows[0];
          console.log("备选方案找到上一站:", prevStation);

          if (!prevStation.name) {
            console.error("上一站数据缺少name字段:", prevStation);
            this.$message.error("无法找到上一站信息");
            this.distanceLoading = false;
            return;
          }

          // 确保高德地图API已初始化
          if (!this.geocoder || !this.AMap) {
            this.initAMap().then(() => {
              this.calculateGaodeDistance(prevStation.name, this.form.name, prevStation.km);
            }).catch(err => {
              this.$message.error("初始化高德地图API失败: " + err.message);
              this.distanceLoading = false;

              // 降级处理：使用简单的预估距离
              const kmValue = 50.0.toFixed(1); // 固定预估为50公里
              this.form.km = kmValue;
              this.$message.warning(`API调用失败，使用预估里程：${kmValue}公里`);
            });
          } else {
            this.calculateGaodeDistance(prevStation.name, this.form.name, prevStation.km);
          }
        } else {
          console.error("未找到上一站数据:", response);
          this.$message.error("无法找到上一站信息");
          this.distanceLoading = false;

          // 添加应急方案：如果无法获取上一站，使用预估值
          const estimatedKm = 50.0.toFixed(1); // 固定预估为50公里
          this.form.km = estimatedKm;
          this.$message.warning(`无法获取上一站信息，使用预估里程：${estimatedKm}公里`);
          this.distanceLoading = false;
        }
      }).catch(err => {
        console.error("查询上一站失败:", err);
        this.distanceLoading = false;
        this.$message.error("获取上一站信息失败");

        // 添加应急方案：如果无法获取上一站，使用预估值
        const estimatedKm = 50.0.toFixed(1); // 固定预估为50公里
        this.form.km = estimatedKm;
        this.$message.warning(`无法获取上一站信息，使用预估里程：${estimatedKm}公里`);
      });
    },
    // 调用高德API计算两站点之间的距离
    calculateGaodeDistance(city1, city2, prevKm) {
      if (!this.geocoder || !this.AMap) {
        this.$message.error("高德地图API未初始化");
        this.distanceLoading = false;
        return;
      }

      Promise.all([
        // 获取第一个城市的坐标
        new Promise((resolve, reject) => {
          this.geocoder.getLocation(city1, (status, result) => {
            if (status === 'complete' && result.geocodes.length) {
              resolve(result.geocodes[0].location);
            } else {
              reject(new Error(`无法获取 ${city1} 的坐标`));
            }
          });
        }),
        // 获取第二个城市的坐标
        new Promise((resolve, reject) => {
          this.geocoder.getLocation(city2, (status, result) => {
            if (status === 'complete' && result.geocodes.length) {
              resolve(result.geocodes[0].location);
            } else {
              reject(new Error(`无法获取 ${city2} 的坐标`));
            }
          });
        })
      ]).then(([location1, location2]) => {
        // 使用高德地图API计算直线距离
        const distance = this.AMap.GeometryUtil.distance(
          [location1.lng, location1.lat],
          [location2.lng, location2.lat]
        );

        // 转换为公里并取整
        const distanceInKm = Math.round(distance / 100) / 10; // 精确到小数点后1位

        // 直接使用计算出的距离值，而不是累加到上一站的总里程
        this.form.km = distanceInKm.toFixed(1);
        this.distanceLoading = false;
      }).catch(err => {
        console.error('高德地图计算距离出错:', err);
        this.$message.error("计算距离失败: " + err.message);
        this.distanceLoading = false;

        // 降级处理：使用简单的预估距离
        const kmValue = 50.0.toFixed(1); // 固定预估为50公里
        this.form.km = kmValue;
        this.$message.warning(`API调用失败，使用预估里程：${kmValue}公里`);
      });
    },
    // 计算站点距离（使用高德地图）
    calculateStationDistance() {
      if (this.form.index === 0 || this.form.index === '0') {
        this.form.km = "0";
        this.$message.info("起始站里程固定为0");
        return;
      }

      if (!this.form.trainCode || !this.form.name) {
        this.$message.warning("请先选择车次和站名");
        return;
      }

      this.calculateDistanceWithGaode();
    },
    // 计算停站时长
    calculateStopTime() {
      if (this.form.inTime && this.form.outTime) {
        try {
          const inTimeParts = this.form.inTime.split(':').map(Number);
          const outTimeParts = this.form.outTime.split(':').map(Number);

          const inDate = new Date();
          inDate.setHours(inTimeParts[0], inTimeParts[1], inTimeParts[2]);

          const outDate = new Date();
          outDate.setHours(outTimeParts[0], outTimeParts[1], outTimeParts[2]);

          if (outDate < inDate) {
            outDate.setDate(outDate.getDate() + 1);
          }

          const diffMs = outDate - inDate;
          const hours = Math.floor(diffMs / (60 * 60 * 1000));
          const minutes = Math.floor((diffMs % (60 * 60 * 1000)) / (60 * 1000));
          const seconds = Math.floor((diffMs % (60 * 1000)) / 1000);

          this.form.stopTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        } catch (e) {
          console.error("计算停站时长错误:", e);
        }}
      },
    // 格式化时间显示
    formatTimeDisplay(time) {
      if (!time) return "--:--:--";
      if (typeof time === 'string') {
        return time;
      }
      try {
        const date = new Date(time);
        if (isNaN(date.getTime())) return "--:--:--";

        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');

        return `${hours}:${minutes}:${seconds}`;
      } catch (e) {
        console.error("时间格式化错误:", e);
        return "--:--:--";
      }
    },
    // 上传文件方法
    submitUpload() {
      this.$refs.upload.submit();
      this.importOpen = false;
    },
    // 上传成功回调
    handleExcelSuccess(response, file) {
      this.importOpen = false;
      this.$refs.upload.clearFiles();

      // 部分导入失败时（发生验证错误）
      if (response.code === 500 && response.data) {
        // 保存错误数据
        this.importErrorData = response.data.map(item => {
          // 添加调试日志，查看数据
          console.log('处理错误数据项:', JSON.stringify(item));

          // 特别处理站序字段
          let indexValue = null;
          if (item.index === 0 || item.index === '0') {
            indexValue = 0;
          } else if (item.index) {
            indexValue = item.index;
          } else {
            indexValue = null; // 明确设为null
          }

          return {
            id: item.id, // 保留原始ID
            rowNum: item.rowNum !== undefined ? item.rowNum : null,
            trainCode: item.trainCode || '',
            index: indexValue, // 使用处理后的值
            name: item.name || '',
            namePinyin: item.namePinyin || '',
            inTime: item.inTime || '',
            outTime: item.outTime || '',
            stopTime: item.stopTime || '',
            km: item.km !== undefined && item.km !== '' ? item.km : (item.km === '0' ? '0' : ''),
            errorMsg: item.errorMsg || "数据验证失败"
          };
        });

        // 显示错误按钮
        this.showImportError = true;

        // 获取成功导入的数量
        const successCount = response.successCount || 0;
        this.importSuccessCount = successCount; // 保存成功导入的数量

        // 根据成功数量显示不同的提示信息
        if (successCount > 0) {
          this.$modal.msgWarning({
            message: `导入部分完成: 成功导入 ${successCount} 条记录，${this.importErrorData.length} 条记录有错误。您可以"导出错误数据"或"查看错误详情"进行处理。`,
            duration: 5000,
            showClose: true
          });
        } else {
          this.$modal.msgError({
            message: `导入失败: ${this.importErrorData.length} 条记录有错误，未能导入任何数据。您可以"导出错误数据"或"查看错误详情"进行处理。`,
            duration: 5000,
            showClose: true
          });
        }

        // 无论如何刷新列表，显示已导入的记录
        this.getList();
      } else if (response.code === 200) {
        // 全部导入成功的情况
        this.importSuccessCount = 0; // 重置成功计数
        let successMsg = "导入成功";
        if (response.msg) {
          successMsg = response.msg;
        }
        this.$modal.msgSuccess(successMsg);
        this.getList();
          } else {
        // 处理其他类型的错误
        this.importSuccessCount = 0; // 重置成功计数
        this.$modal.msgError(response.msg || "导入失败，请联系系统管理员");
      }
    },
    // 上传失败回调
    handleExcelError(err, file) {
      console.error("上传失败:", err);
      this.importOpen = false;

      let errorMsg = "上传Excel失败，请重试";

      // 尝试从错误响应中提取更详细的信息
      if (err && err.message) {
        errorMsg = `上传失败: ${err.message}`;
      } else if (err && err.response && err.response.data) {
        const responseData = err.response.data;
        if (responseData.msg) {
          errorMsg = `上传失败: ${responseData.msg}`;
        } else if (typeof responseData === 'string') {
          errorMsg = `上传失败: ${responseData}`;
        }
      }

      // 检查是否为并发修改异常
      if (errorMsg.includes("ConcurrentModificationException")) {
        errorMsg = "导入失败: 数据检验过程中发生错误，可能存在重复数据，请检查Excel文件并重试";
      }

      this.$modal.msgError(errorMsg);
      this.$refs.upload.clearFiles(); // 清空已上传的文件列表
    },
    // 上传前的文件校验
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过5MB!');
        return false;
      }
      return isExcel && isLt5M;
    },
    // 文件超出数量限制时的处理
    handleExceed(files, fileList) {
      this.$message.warning('只能上传一个文件');
    },
    // 文件改变事件
    handleFileChange(file, fileList) {
      this.fileSelected = fileList.length > 0;
    },
    /** 导出按钮操作 */
    handleExport() {
      const exportParams = { ...this.queryParams };
      // 删除分页相关参数
      delete exportParams.pageNum;
      delete exportParams.pageSize;
      this.download('base/train-station/export', {
        exportParams
      }, `途径车站_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.importOpen = true;
      this.title = "车站数据导入";

      // 重置文件选择状态
      this.fileSelected = false;
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    },
    /** 下载模板操作 */
    handleDownloadTemplate() {
      this.download('base/train-station/downloadTemplate', {}, `途径车站模板_${new Date().getTime()}.xlsx`);
    },
    // 显示示例图片
    showExampleImage() {
      this.exampleImageVisible = true;
    },
    /** 导出错误数据 */
    handleExportErrorData() {
      this.$modal.loading("正在导出数据，请稍候...");

      // 确保错误数据完整，但不修改ID
      const processedData = this.importErrorData.map(item => {
        // 直接返回原始数据，不修改ID
        return { ...item };
      });

      // 直接传递处理后的错误数据到后端
      const formData = new FormData();
      formData.append("errorData", JSON.stringify(processedData));

      // 发送POST请求
      fetch(process.env.VUE_APP_BASE_API + "/base/train-station/exportErrorData", {
        method: "POST",
        body: formData,
        headers: {
          // 添加认证token
          "Authorization": "Bearer " + this.$store.getters.token
        }
      })
      .then(response => {
        if (response.ok) {
          return response.blob();
        }
        throw new Error("导出失败");
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        a.download = "途径车站导入错误数据_" + new Date().getTime() + ".xlsx";
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        this.$modal.closeLoading();
        this.$modal.msgSuccess("导出成功");
      })
      .catch(error => {
        console.error("导出错误:", error);
        this.$modal.closeLoading();
        this.$modal.msgError("导出失败，请重试");
      });
    },
    // 复制错误数据到剪贴板
    handleCopyErrorData() {
      if (!this.importErrorData || this.importErrorData.length === 0) {
        this.$modal.msgError("没有错误数据可复制");
            return;
          }

      const header = ['ID', '行号', '车次编号', '站序', '站名', '站名拼音', '进站时间', '出站时间', '停站时长', '里程（公里）', '错误原因'].join('\t');
      const rows = this.importErrorData.map(item => {
        // 特别处理站序显示
        let indexDisplay = '--';
        if (item.index === 0) {
          indexDisplay = '0';
        } else if (item.index) {
          indexDisplay = item.index;
        }

        return [
          // 确保显示ID值
          item.id || '--',
          // 确保行号为0时不会被替换为'--'
          item.rowNum !== undefined && item.rowNum !== '' ? item.rowNum : '--',
          item.trainCode || '--',
          // 使用处理后的站序显示
          indexDisplay,
          item.name || '--',
          item.namePinyin || '--',
          item.inTime || '--',
          item.outTime || '--',
          item.stopTime || '--',
          // 确保里程为0时正确显示为'0'而不是'--'
          item.km !== undefined && item.km !== '' ? item.km : (item.km === '0' ? '0' : '--'),
          item.errorMsg || '--'
        ].join('\t');
      });

      const text = [header, ...rows].join('\n');

      const textarea = document.createElement('textarea');
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();

      try {
        document.execCommand('copy');
        this.$modal.msgSuccess('错误数据已复制到剪贴板');
      } catch (err) {
        this.$modal.msgError('复制失败，请重试');
      } finally {
        document.body.removeChild(textarea);
      }
    },
    // 获取特定类型错误的数量
    getErrorCount(type) {
      if (!this.importErrorData || this.importErrorData.length === 0) {
        return { count: 0, messages: [] };
      }

      const errorMessages = [];
      let count = 0;

      this.importErrorData.forEach(item => {
        const errorMsg = item.errorMsg || "";
        if (
          (type === 'train code' && errorMsg.includes('车次编号')) ||
          (type === 'duplicated' && errorMsg.includes('重复')) ||
          (type === 'index' && errorMsg.includes('站序')) ||
          (type === 'name' && errorMsg.includes('站名')) ||
          (type === 'time' && (errorMsg.includes('时间') || errorMsg.includes('进站') || errorMsg.includes('出站'))) ||
          (type === 'format' && errorMsg.includes('格式'))
        ) {
          count++;
          errorMessages.push(errorMsg);
        }
      });

      return { count, messages: errorMessages };
    },
    // 获取车次编号的过滤器选项
    getTrainCodeFilters() {
      if (!this.importErrorData) return [];

      const trainCodes = [...new Set(this.importErrorData.map(item => item.trainCode).filter(code => code))];
      return trainCodes.map(code => ({ text: code, value: code }));
    },

    // 过滤车次编号
    filterTrainCode(value, row) {
      return row.trainCode === value;
    },

    // 获取错误类型的过滤器选项
    getErrorTypeFilters() {
      if (!this.importErrorData) return [];

      const errorTypes = [
        { text: '车次错误', value: '车次' },
        { text: '站序错误', value: '站序' },
        { text: '站名错误', value: '站名' },
        { text: '时间错误', value: '时间' },
        { text: '里程错误', value: '里程' },
        { text: '格式错误', value: '格式' }
      ];

      return errorTypes;
    },

    // 过滤错误类型
    filterErrorType(value, row) {
      return row.errorMsg && row.errorMsg.includes(value);
    },

    // 重新导入
    handleRetryImport() {
      this.importOpen = true;
      this.importErrorVisible = false;
    },
    // 清空按钮操作
    handleClear() {
      this.clearOpen = true;
      this.title = "清空列车站点数据";
    },
    // 提交清空表单
    submitClearForm() {
      this.$refs["clearForm"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否确认清空所有列车站点数据？').then(() => {
            return clearTrainStation({ password: this.clearForm.password });
          }).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("清空成功");
              this.clearOpen = false;
              // 重置导入错误相关的状态
              this.importErrorData = [];
              this.showImportError = false;
              // 重置密码表单
              this.resetClearForm();
              this.getList();
          } else {
              this.$modal.msgError(response.msg || "清空失败");
            }
          }).catch(error => {
            console.error("清空失败:", error);
            this.$modal.msgError("清空失败：" + (error.msg || "未知错误"));
          });
        }
      });
    },
    // 取消清空对话框
    cancelClear() {
      this.clearOpen = false;
      this.resetClearForm();
    },
    // 重置清空表单
    resetClearForm() {
      this.clearForm = {
        password: ''
      };
      this.resetForm("clearForm");
    },
    // 出站时间变更
    handleOutTimeChange(time) {
      if (!time) return;

      // 检查是否小于上一站出站时间
      if (this.lastStationOutTime && this.form.index !== 0) {
        const outTime = new Date(`2000/01/01 ${time}`);
        const lastOutTime = new Date(`2000/01/01 ${this.lastStationOutTime}`);

        if (outTime < lastOutTime) {
          this.$message.error(`出站时间不能早于上一站出站时间 ${this.lastStationOutTime}`);
          this.form.outTime = null;
          return;
        }
      }

      // 如果已设置出站时间，重新计算停站时长
      if (this.form.inTime) {
        this.calculateStopTime();
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  .full-width {
    width: 100%;
  }
}

.train-collapse-title {
  display: flex;
  align-items: center;
  gap: 12px;

.train-code {
  font-weight: bold;
  font-size: 16px;
    min-width: 80px;
}

.route-info {
  display: flex;
  align-items: center;
    color: #606266;
    margin-right: 15px;

.route-arrow {
      margin: 0 5px;
    }
}

.route-stats {
  display: flex;
    gap: 15px;
    color: #909399;
    font-size: 13px;
  }
}

.form-tip {
  margin-top: 5px;
  line-height: 1.4;

  i {
    margin-right: 3px;
  }
}

:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  cursor: not-allowed;
}

:deep(.el-input.is-disabled .el-input__suffix) {
  cursor: not-allowed;
}

/* 紧凑型表格样式 */
.compact-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #EBEEF5;
  table-layout: fixed;
}

.compact-table th, .compact-table td {
  border: 1px solid #EBEEF5;
  padding: 8px 6px;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.compact-table th {
  background-color: #F5F7FA;
  font-weight: bold;
  font-size: 13px;
}

/* 对话框样式 */
:deep(.zero-padding-dialog .el-dialog__body) {
  padding: 10px !important;
}

:deep(.zero-padding-dialog .el-dialog__header) {
  padding: 10px !important;
}

/* 导入错误对话框相关样式 */
.import-error-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.error-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.error-summary {
  display: flex;
  align-items: center;
  font-size: 15px;
}

.error-actions {
  display: flex;
  gap: 10px;
}

:deep(.el-table .warning-row) {
  background: #fdf5e6;
}

:deep(.el-table .error-row) {
  background: #fef0f0;
}

/* 上传组件样式 */
.upload-demo {
  margin-top: 20px;
}

.el-upload__tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

/* 表单验证提示样式 */
.el-form-item__error {
  color: #F56C6C;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0;
}

/* 加载状态样式 */
.distance-loading {
  display: inline-block;
  margin-left: 10px;
  vertical-align: middle;
}

/* 折叠面板样式 */
.el-collapse-item__header {
  font-size: 14px;
  color: #303133;
  cursor: pointer;
  transition: border-bottom-color .3s;
  outline: 0;
}

.el-collapse-item__wrap {
  will-change: height;
  background-color: #fff;
  overflow: hidden;
  box-sizing: border-box;
  border-bottom: 1px solid #EBEEF5;
}

/* 表格操作按钮样式 */
.el-button--text {
  padding: 0;
  margin: 0 5px;
}

/* 分页组件样式 */
.pagination-container {
  padding: 20px 0;
  text-align: right;
}

/* 搜索表单样式 */
.el-form--inline {
  margin-bottom: 20px;
}

/* 按钮组样式 */
.mb8 {
  margin-bottom: 8px;
}

/* 对话框底部按钮样式 */
.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

/* 导入提示样式 */
.import-tip {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

/* 错误信息样式 */
.error-message {
  color: #F56C6C;
  font-size: 13px;
  margin-top: 5px;
}

/* 成功信息样式 */
.success-message {
  color: #67C23A;
  font-size: 13px;
  margin-top: 5px;
}

/* 警告信息样式 */
.warning-message {
  color: #E6A23C;
  font-size: 13px;
  margin-top: 5px;
}

/* 信息提示样式 */
.info-message {
  color: #909399;
  font-size: 13px;
  margin-top: 5px;
}

.error-operation {
  margin: 15px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-tooltip__popper {
  max-width: 400px;
  white-space: normal;
  word-wrap: break-word;
}

.el-dialog__title {
  font-weight: bold;
}

p {
  margin: 10px 0;
  line-height: 1.5;
}

.el-table {
  margin-top: 15px;
  .el-table__row:hover {
    background-color: #f5f7fa;
  }
}
</style>
